package com.wtwd.device.netty;


import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.handler.MsgHandler;
import com.wtwd.device.protocol.AppProtocol;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ChannelHandler.Sharable
public class BaseChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{

    private static final Logger log = LoggerFactory.getLogger(BaseChannelHandler.class);

    @Resource
    private MsgHandler msgHandler;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        log.info("channelActive:{}-{} online", incoming.remoteAddress(), incoming.id());
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        log.info("channelId:{}：{}", ctx.channel().id(), textWebSocketFrame.text());
        String data = textWebSocketFrame.text();
        AppProtocol protocol = JSONObject.parseObject(data, AppProtocol.class);
        msgHandler.processMessage(protocol, ctx.channel());
    }

    public static void main(String[] args) {
        String app_login = JSONObject.toJSONString(AppProtocol.builder().imei("123456").cmdName("APP_LOGIN").build());
        System.out.println(app_login);
    }


    /**
     * 客户端断开连接
     * 设备下线及关闭管道
     *
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        log.error("客户端断开连接:{}", incoming.id());
        AppProtocol protocol = AppProtocol.builder().cmdName(MsgTypeEnum.APP_OFFLINE.getCmdName())
                .build();
        msgHandler.processMessage(protocol, incoming);
        ctx.close();
    }

    /**
     * 异常处理
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel incoming = ctx.channel();
        log.info("异常处理:{}-{}", incoming.id(), cause.toString());
        ctx.close();
    }


}
